package socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;



public class SocketClient {

	private static Socket client;
	static SocketClient  clientsocket;
	
	static  public SocketClient getInstance()
	{
		if (clientsocket == null)
		{
			clientsocket = new  SocketClient("192.168.0.101", 5567);
		}
		else{
			return clientsocket;
		}
		
		return clientsocket;
	}
	
	private  SocketClient(String servername, int port) {
		try {
			client = new Socket(servername, port);
			System.out.println("Create Socket" + servername + " " + port);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public byte[] sendMsg(String msg) {

		try {
			PrintWriter out = new PrintWriter(client.getOutputStream());
			out.println(msg);
			out.flush();
			return recvMsg(1028);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public byte[] recvMsg(int needrecvlen)
	{
		int len;
		int recvlen = needrecvlen;
		int index = 0;
		byte [] buf = new byte[needrecvlen];
		byte [] buff = new byte[needrecvlen];
		try{
			InputStream  in = client.getInputStream();
		
			try{
				
			    while(recvlen != 0)
			    {
					len = in.read(buf, 0, recvlen);
					if(len > 0)
					{
						recvlen -= len;
						System.arraycopy(buf, 0, buff, index, len);
						index += len;	
					}
			    }
			    return buff;
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}
			
		}catch(IOException e)
		{
			e.printStackTrace();
		}
		
		return null;
	}
	
	
	public void closeSocket() {
		try {
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}